<?php 
class Country_AdminManageCountryController extends Core_Controller_Action_Admin{
    
    public function pollListAction(){
        $this->view->navigation = $navigation = Engine_Api::_()->getApi('menus', 'core')
                ->getNavigation('country_admin_main', array(), 'country_admin_main_polllist');
        
        $country_id = $this->_getParam('country_id',$this->_getParam('id',0));
        $this->view->country_id = $country_id;
                           
        $table = Engine_Api::_()->getDbtable('polls','country');
        $select = $table->select();
                        
                                                
        $this->view->paginator = $paginator = Zend_Paginator::factory($select);
        $page = $this->_getParam('page',1);
        $paginator->setItemCountPerPage(20);
        $this->view->paginator = $paginator->setCurrentPageNumber($page);
    }
    
    public function addPollAction(){
        if( !$this->_helper->requireUser()->isValid() ) {
          return;
        }
        
        $this->view->navigation = $navigation = Engine_Api::_()->getApi('menus', 'core')
                ->getNavigation('country_admin_main', array(), 'country_admin_main_addpoll');
       
            
        $this->view->options = array();
        $this->view->maxOptions = $max_options = Engine_Api::_()->getApi('settings', 'core')->getSetting('poll.maxoptions', 15);
        $this->view->form = $form = new Country_Form_Poll_Create();
        $form->removeElement('auth_view');
        $form->removeElement('auth_comment');
        $form->removeElement('search');
        
        $viewer = Engine_Api::_()->user()->getViewer();
    
        if( !$this->getRequest()->isPost() ) {
          return;
        }
    
        if( !$form->isValid($this->getRequest()->getPost()) ) {
          return;
        }
        
        // Check options
        $options = (array) $this->_getParam('optionsArray');
        $options = array_filter(array_map('trim', $options));
        $options = array_slice($options, 0, $max_options);
        $this->view->options = $options;
        if( empty($options) || !is_array($options) || count($options) < 2 ) {
          return $form->addError('You must provide at least two possible answers.');
        }
        foreach( $options as $index => $option ) {
          if( strlen($option) > 80 ) {
            $options[$index] = Engine_String::substr($option, 0, 80);
          }
        }
    
        // Process
        $pollTable = Engine_Api::_()->getDbtable('polls','country');;
        $pollOptionsTable = Engine_Api::_()->getDbtable('polloptions', 'country');
        $db = $pollTable->getAdapter();
        $db->beginTransaction();
    
        try {
          $values = $form->getValues();
          $values['user_id'] = $viewer->getIdentity();
          
          // Create poll
          $poll = $pollTable->createRow();
          $poll->setFromArray($values);
          $poll->save();
    
          // Create options
          $censor = new Engine_Filter_Censor();
          $html = new Engine_Filter_Html(array('AllowedTags'=> array('a')));
          foreach( $options as $option ) {
            $option = $censor->filter($html->filter($option));
            $pollOptionsTable->insert(array(
              'poll_id' => $poll->getIdentity(),
              'title' => $option,
            ));
          }
            
          
          $db->commit();
          $form->addNotice('You had add success poll.');
        } catch( Exception $e ) {
          $db->rollback();
          throw $e;
        }
    
        
    }
    
    public function removePollAction(){
        $poll_id = $this->_getParam('poll_id',0);
        $this->view->form = $form = new Country_Form_Delete();
        $form->setTitle('Delete Poll');
        $form->setDescription('Could you want to delete this poll?');
        $form->getElement('submit')->setLabel('Yes');
        if ($this->getRequest()->isPost()) {
            
            $pollT = Engine_Api::_()->getDbtable('polls','country');
            $pollT->removePoll($poll_id);
            
            return   $this->_forward('success', 'utility', 'core', array(
                    'smoothboxClose' => 1000,
                    'parentRefresh'=> 1000,
                    'messages' => array($this->view->translate('This poll had been deleted successed.'))
           	));
            
        }
        
        
    }
    
    public function editPollAction(){
        
        $this->view->navigation = $navigation = Engine_Api::_()->getApi('menus', 'core')
                ->getNavigation('country_admin_main', array(), 'country_admin_main_addpoll');
       
        $poll_id = $this->_getParam('poll_id',0);
        if (empty($poll_id)) {
            return   $this->_forward('success', 'utility', 'core', array(
                    'smoothboxClose' => 1000,
                    'messages' => array($this->view->translate('Can not found you poll.'))
           	));
        }    
        
        $viewer = Engine_Api::_()->user()->getViewer();
        
        $poll = Engine_Api::_()->getItem('country_poll',$poll_id);
        if (!$poll){
            return   $this->_forward('success', 'utility', 'core', array(
                    'smoothboxClose' => 1000,
                    'messages' => array($this->view->translate('Can not found you poll.'))
           	));
        }
        $this->view->poll = $poll;
        
        $this->view->options = array();
        $this->view->maxOptions = $max_options = Engine_Api::_()->getApi('settings', 'core')->getSetting('poll.maxoptions', 15);
        $this->view->form = $form = new Country_Form_Poll_Create();
        $form->removeElement('auth_view');
        $form->removeElement('auth_comment');
        $form->removeElement('search');
        $form->getElement('submit')->setLabel('Edit');
        
        if (!$this->getRequest()->isPost()) {
            $options = array();
            $pollOptions = $poll->getOptions();
            foreach($pollOptions as $obj){
                $options[$obj->polloption_id] = $obj->title;
            }
            $form->getElement('title')->setValue($poll->title);
            $form->getElement('description')->setValue($poll->description);
            $form->getElement('poll_type')->setValue($poll->poll_type);
            
            $this->view->options = $options;
            return;
        }
        
        if( !$form->isValid($this->getRequest()->getPost()) ) {
          return;
        }
        
        // Check options
        $options = (array) $this->_getParam('optionsArray');
        $options = array_filter(array_map('trim', $options));
        $options = array_slice($options, 0, $max_options);
        $this->view->options = $options;
        if( empty($options) || !is_array($options) || count($options) < 2 ) {
          return $form->addError('You must provide at least two possible answers.');
        }
        foreach( $options as $index => $option ) {
          if( strlen($option) > 80 ) {
            $options[$index] = Engine_String::substr($option, 0, 80);
          }
        }
    
        // Process
        $pollTable = Engine_Api::_()->getDbtable('polls','country');;
        $pollOptionsTable = Engine_Api::_()->getDbtable('polloptions', 'country');
        $db = $pollTable->getAdapter();
        $db->beginTransaction();
    
        try {
          $values = $form->getValues();
          $values['user_id'] = $viewer->getIdentity();
          
         
          $poll->setFromArray($values);
          $poll->save();
          
          $poll->deleteOptions();
            
          // Create options
          $censor = new Engine_Filter_Censor();
          $html = new Engine_Filter_Html(array('AllowedTags'=> array('a')));
          foreach( $options as $option ) {
            $option = $censor->filter($html->filter($option));
            $pollOptionsTable->insert(array(
              'poll_id' => $poll->getIdentity(),
              'title' => $option,
            ));
          }
            
          
          $db->commit();
          return   $this->_forward('success', 'utility', 'core', array(
                    'smoothboxClose' => 1000,
                    'parentRefresh'=> 1000,
                    'messages' => array($this->view->translate('Your poll had been change successed'))
           	));
        } catch( Exception $e ) {
          $db->rollback();
          return   $this->_forward('success', 'utility', 'core', array(
                    'smoothboxClose' => 1000,
                    'messages' => array($this->view->translate('There error, please try again.'))
           	));
        }
    
        
    }
    
    public function addManagerAction(){
        $country_id = $this->_getParam('cid',0);
        $user_id = $this->_getParam('uid',0);
        $this->view->form = $form = new Country_Form_Delete();
        $form->setTitle('Set memeber to manager');
        $form->setDescription('Could you want to set this member to manager of country?');
        $form->getElement('submit')->setLabel('Yes');
        if ($this->getRequest()->isPost()) {
            
            $managerT = Engine_Api::_()->getDbtable('managers','country');
            if (!$managerT->isManager($country_id,$user_id)) {
                $row = $managerT->createRow();
                $row->user_id = $user_id;
                $row->country_id = $country_id;
                $row->save();
            } 
            
            return   $this->_forward('success', 'utility', 'core', array(
                    'smoothboxClose' => 1000,
                    'parentRefresh'=> 1000,
                    'messages' => array($this->view->translate('This member had been set to manager successed.'))
           	));
            
        }
        
        
    }
    
    public function removeManagerAction(){
        $country_id = $this->_getParam('cid',0);
        $user_id = $this->_getParam('uid',0);
        $this->view->form = $form = new Country_Form_Delete();
        $form->setTitle('Remove manager of country');
        $form->setDescription('Could you want to remove this manager from country?');
        $form->getElement('submit')->setLabel('Yes');
        if ($this->getRequest()->isPost()) {
            
            $managerT = Engine_Api::_()->getDbtable('managers','country');
            $managerT->removeManager($country_id,$user_id);
            
            return   $this->_forward('success', 'utility', 'core', array(
                    'smoothboxClose' => 1000,
                    'parentRefresh'=> 1000,
                    'messages' => array($this->view->translate('This manager had been remove from country successed.'))
           	));
            
        }
        
        
    }
    public function memberToAddAction(){
       
        $this->view->navigation = $navigation = Engine_Api::_()->getApi('menus', 'core')
                ->getNavigation('country_admin_main', array(), 'country_admin_main_addmanager');
        
        $country_id = $this->_getParam('country_id',$this->_getParam('cid',0));
        $this->view->country_id = $country_id;
        
        $managerTa = Engine_Api::_()->getDbtable('managers','country');
        $this->view->listManager = $managerTa->getUserManagerId($country_id);
                         
        $memberCountryT = Engine_Api::_()->getDbtable('countrymembers','country');
        $select = $memberCountryT->select()
                                 ->where('country_id = ?',$country_id);
        $userIds = array();
        $rows = $memberCountryT->fetchAll($select);
        
        $userIds[0] = 0;
        foreach($rows as $row ){
            $userIds[] = $row->user_id;
        }
        
            
        $userTable = Engine_Api::_()->getDbtable('users','user');
        $select = $userTable->select()
                            ->where('user_id in (?)',$userIds);
                                                
        $this->view->paginator = $paginator = Zend_Paginator::factory($select);
        $page = $this->_getParam('page',1);
        $paginator->setItemCountPerPage(20);
        $this->view->paginator = $paginator->setCurrentPageNumber($page);
        
    }
    
    public function manageListAction(){
        $this->view->navigation = $navigation = Engine_Api::_()->getApi('menus', 'core')
                ->getNavigation('country_admin_main', array(), 'country_admin_main_manager');
        
        $country_id = $this->_getParam('country_id',$this->_getParam('id',0));
        $this->view->country_id = $country_id;
                           
        $table = Engine_Api::_()->getDbtable('managers','country');
        $userIds = $table->getUserManagerId($country_id);
        
        $table = Engine_Api::_()->getDbtable('users','user');
        $select = $table->select()
                        ->where('user_id in (?) ',$userIds);
                                                
        $this->view->paginator = $paginator = Zend_Paginator::factory($select);
        $page = $this->_getParam('page',1);
        $paginator->setItemCountPerPage(20);
        $this->view->paginator = $paginator->setCurrentPageNumber($page);
    }
    public function removeManage(){
        $this->view->navigation = $navigation = Engine_Api::_()->getApi('menus', 'core')
                ->getNavigation('country_admin_main', array(), 'country_admin_main_country');
        
        $country_id = $this->_getParam('country_id',0);
        $this->view->country_id = $country_id;
         
        $table = Engine_Api::_()->getDbtable('managers','country');
        $select = $table->where('country_id = ?',$country_id);
                                                
        $select = $table->select();
        $this->view->paginator = $paginator = Zend_Paginator::factory($select);
        $page = $this->_getParam('page',1);
        $paginator->setItemCountPerPage(20);
        $this->view->paginator = $paginator->setCurrentPageNumber($page);
    }
    
    public function indexAction(){
        
        $this->view->navigation = $navigation = Engine_Api::_()->getApi('menus', 'core')
                ->getNavigation('country_admin_main', array(), 'country_admin_main_country');
    
        $table = Engine_Api::_()->getDbTable('countries', 'country');
        $select = $table->select();
        $this->view->paginator = $paginator = Zend_Paginator::factory($select);
        $page = $this->_getParam('page',1);
        $paginator->setItemCountPerPage(20);
        $this->view->paginator = $paginator->setCurrentPageNumber($page);
    }
    
    public function addAction(){
        $request = $this->getRequest();
        
        $viewer = Engine_Api::_()->user()->getViewer();
      	$this->view->form = $form = new Country_Form_Admin_Country_Create();
        $form->setTitle('Create New Country');
        
        if($request->isPost()){
            if(!$form->isValid($request->getPost())) return;
            
            $values = $form->getValues();
            
            try{
            
                $countryTb  = Engine_Api::_()->getDbTable('countries', 'country');
                $country = $countryTb->createRow();
                
                if( !empty($_FILES['new_flag']) && $_FILES['new_flag']['error'] == 0) { // set flag to country
                    $new_flag_id = $country->setPhoto($form->new_flag);
                    $country->flag_photo_id = $new_flag_id;
                }
                if( !empty($_FILES['new_big_map']) && $_FILES['new_big_map']['error'] == 0) { // set big map to country
                    $big_map_id = $country->setPhoto($form->new_big_map);
                    $country->big_map_photo_id = $big_map_id;
                }
                if( !empty($_FILES['new_small_map']) && $_FILES['new_small_map']['error'] == 0) { // set small map to country
                    $small_map_id = $country->setPhoto($form->new_small_map);
                    $country->small_map_photo_id = $small_map_id;
                }
                if( !empty($_FILES['president_image_id']) && $_FILES['president_image_id']['error'] == 0) { // set small map to country
                    $president_image_id = $country->setPhoto($form->president_image_id);
                    $country->president_image_id = $president_image_id;
                }
				
				if( !empty($_FILES['national_anthem_id']) && $_FILES['national_anthem_id']['error'] == 0) { // set national anthem
                    $national_anthem_id = $country->createSong($_FILES['national_anthem_id']);
                    $country->national_anthem_id = $national_anthem_id;
                }
				
                $country->title = $values['country_title']; 
                $country->description = $values['description_country'];
				$country->national_anthem_title = $values['national_anthem_title'];
				$country->president_name = $values['president_name'];
                $country->owner_id = $viewer->getIdentity();
                $country->creation_date = date("Y-m-d H:i:s");
                $country->modified_date = date("Y-m-d H:i:s");
                
                $country->save();
                
                $this->_forward('success', 'utility', 'core', array(
                    'smoothboxClose' => 10,
                    'parentRefresh'=> 10,
                    'messages' => array($this->view->translate('Adding Successfully.'))
            	));
            
            }
            catch(exception $e){
                $this->_forward('success', 'utility', 'core', array(
                    'smoothboxClose' => 1000,
                    'parentRefresh'=> 10,
                    'messages' => array($this->view->translate('Adding Error.'))
            	));
            }
            
        }
    }
    
    public function editAction(){
        
        $request = $this->getRequest();
        $country_id = $request->getParam('id',0);
      	$country = Engine_Api::_()->getItem('country_country', $country_id);
        if(!$country) return;
        
        $this->view->form = $form = new Country_Form_Admin_Country_Create();
        
        $populate_array = array();
        
        
        $populate_array['country_title'] = $country->title;
        $populate_array['description_country'] = $country->description;
		$populate_array['national_anthem_title'] = $country->national_anthem_title;
		$populate_array['president_name'] = $country->president_name;
        $form->populate($populate_array);
        
        $viewer = Engine_Api::_()->user()->getViewer();
      	
        $form->setTitle('Edit this country');
        
         if($request->isPost()){
			$form->getElement('new_flag')->setOptions(array('required' => false));
			$form->getElement('new_big_map')->setOptions(array('required' => false));
			$form->getElement('new_small_map')->setOptions(array('required' => false));
            if(!$form->isValid($request->getPost())) return;
            
            $values = $form->getValues();
            
            try{
                
                if( !empty($_FILES['new_flag']) && $_FILES['new_flag']['error'] == 0) { // set flag to country
                    $new_flag_id = $country->setPhoto($form->new_flag);
                    $country->flag_photo_id = $new_flag_id;
                }
                if( !empty($_FILES['new_big_map']) && $_FILES['new_big_map']['error'] == 0) { // set big map to country
                    $big_map_id = $country->setPhoto($form->new_big_map);
                    $country->big_map_photo_id = $big_map_id;
                }
                if( !empty($_FILES['new_small_map']) && $_FILES['new_small_map']['error'] == 0) { // set small map to country
                    $small_map_id = $country->setPhoto($form->new_small_map);
                    $country->small_map_photo_id = $small_map_id;
                }
				 if( !empty($_FILES['president_image_id']) && $_FILES['president_image_id']['error'] == 0) { // set small map to country
                    $president_image_id = $country->setPhoto($form->president_image_id);
                    $country->president_image_id = $president_image_id;
                }
				
				if( !empty($_FILES['national_anthem_id']) && $_FILES['national_anthem_id']['error'] == 0) { // set national anthem
                    $national_anthem_id = $country->createSong($form->national_anthem_id);
                    $country->national_anthem_id = $national_anthem_id;
                }
				
                $country->title = $values['country_title']; 
                $country->description = $values['description_country'];
				$country->national_anthem_title = $values['national_anthem_title'];
				$country->president_name = $values['president_name'];
                $country->owner_id = $viewer->getIdentity();
                
                $country->save();
                
                $this->_forward('success', 'utility', 'core', array(
                    'smoothboxClose' => 10,
                    'parentRefresh'=> 10,
                    'messages' => array($this->view->translate('Adding Successfully.'))
            	));
            
            }
            catch(exception $e){
				throw($e);die;
                $this->_forward('success', 'utility', 'core', array(
                    'smoothboxClose' => 1000,
                    'parentRefresh'=> 10,
                    'messages' => array($this->view->translate('Adding Error.'))
            	));
            }
            
        }
    }
}
?>